<template>
  <div class="post-list-container">
    <!-- 操作按钮区域 -->
    <div class="action-bar">
      <div class="left-actions">
        <el-button type="primary" icon="el-icon-plus" @click="handleAdd">添加帖子</el-button>
        <el-button type="info" icon="el-icon-refresh" @click="getPostsList">刷新</el-button>
      </div>
      <div class="right-actions">
        <el-select v-model="topicFilter" clearable placeholder="按专题筛选" style="width: 160px; margin-right: 10px;">
          <el-option
            v-for="item in topicOptions"
            :key="item.topicId"
            :label="item.topicName"
            :value="item.topicId">
          </el-option>
        </el-select>
        <el-input v-model="searchTitle" placeholder="搜索帖子标题" prefix-icon="el-icon-search" clearable
          class="search-input" @clear="handleSearch" @keyup.enter.native="handleSearch">
          <el-button slot="append" icon="el-icon-search" @click="handleSearch"></el-button>
        </el-input>
      </div>
    </div>
    
    <!-- 帖子列表表格 -->
    <el-card shadow="hover" class="table-card">
      <div class="posts-list" v-loading="loading" element-loading-text="加载中..." element-loading-spinner="el-icon-loading" element-loading-background="rgba(255, 255, 255, 0.7)">
        <el-table
          :data="postsList"
          style="width: 100%"
          border
          stripe
          :header-cell-style="{backgroundColor: '#f5f7fa', color: '#606266'}"
          v-if="postsList.length > 0"
        >
          <el-table-column prop="postId" label="帖子ID" width="200" align="center"></el-table-column>
          <el-table-column prop="title" label="标题" min-width="150">
            <template slot-scope="scope">
              <el-tooltip :content="scope.row.title" placement="top" :disabled="scope.row.title.length < 20">
                <span>{{ scope.row.title.length > 20 ? scope.row.title.substring(0, 20) + '...' : scope.row.title }}</span>
              </el-tooltip>
            </template>
          </el-table-column>
          <el-table-column prop="topicName" label="所属专题" width="120" align="center">
            <template slot-scope="scope">
              <el-tag type="primary">{{ getTopicName(scope.row.topicId) }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="userName" label="发帖人" width="100" align="center"></el-table-column>
          <el-table-column label="浏览/点赞/评论" width="140" align="center">
            <template slot-scope="scope">
              <el-tooltip content="浏览量" placement="top">
                <span><i class="el-icon-view" style="color: #409EFF;"></i> {{ scope.row.views }}</span>
              </el-tooltip>
              <span style="margin: 0 5px;">|</span>
              <el-tooltip content="点赞数" placement="top">
                <span><i class="fas fa-heart" style="color: #ff4757;"></i> {{ scope.row.likes }}</span>
              </el-tooltip>
              <span style="margin: 0 5px;">|</span>
              <el-tooltip content="评论数" placement="top">
                <span><i class="el-icon-chat-dot-round" style="color: #67C23A;"></i> {{ scope.row.comments }}</span>
              </el-tooltip>
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="发布时间" width="170" align="center">
            <template slot-scope="scope">
              {{ formatDate(scope.row.createTime) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="180" align="center">
            <template slot-scope="scope">
              <el-button-group class="operation-btns">
                <!-- <el-tooltip content="编辑" placement="top">
                  <el-button type="primary" size="mini" icon="el-icon-edit" @click="handleEdit(scope.row)"></el-button>
                </el-tooltip> -->
                <el-tooltip content="查看" placement="top">
                  <el-button type="info" size="mini" icon="el-icon-view" @click="handleView(scope.row)"></el-button>
                </el-tooltip>
                <el-tooltip content="删除" placement="top">
                  <el-button type="danger" size="mini" icon="el-icon-delete" @click="handleDelete(scope.row)"></el-button>
                </el-tooltip>
              </el-button-group>
            </template>
          </el-table-column>
        </el-table>
        
        <el-empty v-if="postsList.length === 0" description="暂无帖子数据"></el-empty>
      </div>
      
      <!-- 分页组件 -->
      <div class="pagination-container">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pageNum"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          background
        >
        </el-pagination>
      </div>
    </el-card>

    <!-- 新增/编辑帖子对话框 -->
    <el-dialog
      :title="dialogType === 'add' ? '新增帖子' : '编辑帖子'"
      :visible.sync="dialogVisible"
      width="700px"
      @close="resetForm"
      center
    >
      <el-form :model="postForm" :rules="formRules" ref="postForm" label-width="80px" status-icon>
        <el-form-item label="标题" prop="title">
          <el-input v-model="postForm.title" placeholder="请输入帖子标题"></el-input>
        </el-form-item>
        <el-form-item label="专题" prop="topicId">
          <el-select v-model="postForm.topicId" placeholder="请选择专题" style="width: 100%;">
            <el-option
              v-for="item in topicOptions"
              :key="item.topicId"
              :label="item.topicName"
              :value="item.topicId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <el-input
            type="textarea"
            :rows="12"
            placeholder="请输入帖子内容"
            v-model="postForm.content"
          ></el-input>
        </el-form-item>
        <el-form-item label="媒体文件" v-if="dialogType === 'edit'">
          <div class="media-preview" v-if="postForm.mediaUrl">
            <div class="media-item">
              <img v-if="postForm.mediaType.includes('image')" :src="postForm.mediaUrl" class="media-thumbnail" />
              <video v-else-if="postForm.mediaType.includes('video')" :src="postForm.mediaUrl" controls class="media-thumbnail"></video>
              <div v-else class="file-placeholder">
                <i class="el-icon-document"></i>
                <span>{{ postForm.mediaUrl.split('/').pop() }}</span>
              </div>
            </div>
          </div>
          <div v-else>无媒体文件</div>
        </el-form-item>
      </el-form>
      
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm" :loading="submitting">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 查看帖子详情对话框 -->
    <el-dialog
      title="帖子详情"
      :visible.sync="viewDialogVisible"
      width="800px"
      center
    >
      <div class="post-detail" v-if="currentPost">
        <el-row :gutter="20">
          <el-col :span="24">
            <el-descriptions class="post-details" :column="1" border>
              <el-descriptions-item label="帖子标题">{{ currentPost.title }}</el-descriptions-item>
              <el-descriptions-item label="所属专题">
                <el-tag type="primary">{{ getTopicName(currentPost.topicId) }}</el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="发布人">{{ currentPost.userName }}</el-descriptions-item>
              <el-descriptions-item label="发布时间">{{ formatDate(currentPost.createTime) }}</el-descriptions-item>
              <el-descriptions-item label="统计数据">
                <div class="post-stats">
                  <span><i class="el-icon-view" style="color: #409EFF;"></i> 浏览: {{ currentPost.views }}</span>
                  <span><i class="fas fa-heart" style="color: #ff4757;"></i> 点赞: {{ currentPost.likes }}</span>
                  <span><i class="el-icon-chat-dot-round" style="color: #67C23A;"></i> 评论: {{ currentPost.comments }}</span>
                </div>
              </el-descriptions-item>
              <el-descriptions-item label="帖子内容">
                <div class="post-content">{{ currentPost.content }}</div>
              </el-descriptions-item>
            </el-descriptions>
          </el-col>
        </el-row>
        
        <div v-if="currentPost.mediaUrl" class="post-media">
          <h3>附件媒体:</h3>
          <img v-if="currentPost.mediaType && currentPost.mediaType.includes('image')" :src="currentPost.mediaUrl" class="media-full" />
          <video v-else-if="currentPost.mediaType && currentPost.mediaType.includes('video')" :src="currentPost.mediaUrl" controls class="media-full"></video>
          <div v-else class="file-item">
            <i class="el-icon-document"></i>
            <a :href="currentPost.mediaUrl" target="_blank">{{ currentPost.mediaUrl.split('/').pop() }}</a>
          </div>
        </div>
      </div>
      
      <span slot="footer" class="dialog-footer">
        <el-button @click="viewDialogVisible = false">关 闭</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import service from '@/utils/request';

export default {
  name: 'PostsManagement',
  data() {
    return {
      // 列表数据
      postsList: [],
      topicOptions: [],
      // 分页相关
      pageNum: 1,
      pageSize: 10,
      total: 0,
      // 筛选条件
      searchTitle: '',
      topicFilter: '',
      // 加载状态
      loading: false,
      submitting: false,
      // 对话框控制
      dialogVisible: false,
      viewDialogVisible: false,
      dialogType: 'add', // add 或 edit
      // 当前查看的帖子
      currentPost: null,
      // 表单数据
      postForm: {
        postId: '',
        title: '',
        content: '',
        topicId: '',
        userId: '',
        mediaUrl: '',
        mediaType: '',
        token: localStorage.getItem('token')
      },
      // 表单验证规则
      formRules: {
        title: [
          { required: true, message: '请输入帖子标题', trigger: 'blur' },
          { min: 2, max: 50, message: '标题长度在 2 到 50 个字符', trigger: 'blur' }
        ],
        topicId: [
          { required: true, message: '请选择专题', trigger: 'change' }
        ],
        content: [
          { required: true, message: '请输入帖子内容', trigger: 'blur' },
          { min: 10, max: 1000, message: '内容长度在 10 到 1000 个字符', trigger: 'blur' }
        ]
      }
    };
  },
  created() {
    this.getTopicOptions();
    this.getPostsList();
  },
  methods: {
    // 格式化日期
    formatDate(dateString) {
      if (!dateString) return '';
      const date = new Date(dateString);
      return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')} ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
    },
    
    // 获取专题选项
    getTopicOptions() {
      service.get('/api/forum/topic/getTopicLists')
        .then(res => {
          if (res.code === 200) {
            this.topicOptions = res.data || [];
          } else {
            this.$message.error(res.msg || '获取专题列表失败');
          }
        })
        .catch(error => {
          console.error('获取专题列表出错:', error);
          this.$message.error('网络错误，请稍后重试');
        });
    },
    
    // 获取帖子列表
    getPostsList() {
      this.loading = true;
      const params = {
        pageNum: this.pageNum,
        pageSize: this.pageSize,
        title: this.searchTitle,
        topicId: this.topicFilter
      };
      
      service.get('/api/forum/post/getPostLists', {params})
        .then(res => {
          if (res.code === 200) {
            this.postsList = res.data.list || [];
            this.total = res.data.total || 0;
          } else {
            this.$message.error(res.msg || '获取帖子列表失败');
          }
        })
        .catch(error => {
          console.error('获取帖子列表出错:', error);
          this.$message.error('网络错误，请稍后重试');
        })
        .finally(() => {
          this.loading = false;
        });
    },
    
    // 搜索处理
    handleSearch() {
      this.pageNum = 1;
      this.getPostsList();
    },
    
    // 分页大小变化
    handleSizeChange(newSize) {
      this.pageSize = newSize;
      this.getPostsList();
    },
    
    // 当前页变化
    handleCurrentChange(newPage) {
      this.pageNum = newPage;
      this.getPostsList();
    },
    
    // 添加帖子
    handleAdd() {
      this.dialogType = 'add';
      this.dialogVisible = true;
      this.resetForm();
    },
    
    // // 编辑帖子
    // handleEdit(row) {
    //   this.dialogType = 'edit';
    //   this.dialogVisible = true;
    //   this.$nextTick(() => {
    //     // 获取帖子详情
    //     service.get(`/api/forum/post/getPostDetail/${row.postId}`)
    //       .then(res => {
    //         if (res.code === 200) {
    //           this.postForm = {
    //             postId: res.data.postId,
    //             title: res.data.title,
    //             content: res.data.content,
    //             topicId: res.data.topicId,
    //             userId: res.data.userId,
    //             mediaUrl: res.data.mediaUrl,
    //             mediaType: res.data.mediaType,
    //             token: localStorage.getItem('token')
    //           };
    //         } else {
    //           this.$message.error(res.msg || '获取帖子详情失败');
    //         }
    //       })
    //       .catch(error => {
    //         console.error('获取帖子详情出错:', error);
    //         this.$message.error('网络错误，请稍后重试');
    //       });
    //   });
    // },
    
    // 查看帖子
    handleView(row) {
      service.get(`/api/forum/post/detail/${row.postId}`)
        .then(res => {
          if (res.code === 200) {
            this.currentPost = res.data;
            this.viewDialogVisible = true;
          } else {
            this.$message.error(res.msg || '获取帖子详情失败');
          }
        })
        .catch(error => {
          console.error('获取帖子详情出错:', error);
          this.$message.error('网络错误，请稍后重试');
        });
    },
    
    // 删除帖子
    handleDelete(row) {
      this.$confirm('此操作将永久删除该帖子及其相关评论, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        service.delete(`/api/forum/post/deletePost/${row.postId}`).then(res => {
          if (res.code === 200) {
            this.$message.success('删除成功');
            this.getPostsList();
          } else {
            this.$message.error(res.msg || '删除失败');
          }
        }).catch(error => {
          console.error('删除帖子出错:', error);
          this.$message.error('网络错误，请稍后重试');
        });
      }).catch(() => {
        // 取消删除
      });
    },
    
    // 提交表单
    submitForm() {
      this.$refs.postForm.validate(valid => {
        if (valid) {
          this.submitting = true;
          const url = this.dialogType === 'add' 
            ? '/api/forum/post/addPost' 
            : '/api/forum/post/updatePost';
          
          service.post(url, this.postForm)
            .then(res => {
              if (res.code === 200) {
                this.$message.success(this.dialogType === 'add' ? '添加成功' : '更新成功');
                this.dialogVisible = false;
                this.getPostsList();
              } else {
                this.$message.error(res.msg || (this.dialogType === 'add' ? '添加失败' : '更新失败'));
              }
            })
            .catch(error => {
              console.error(this.dialogType === 'add' ? '添加帖子出错:' : '更新帖子出错:', error);
              this.$message.error('网络错误，请稍后重试');
            })
            .finally(() => {
              this.submitting = false;
            });
        } else {
          return false;
        }
      });
    },
    
    // 重置表单
    resetForm() {
      this.$nextTick(() => {
        if (this.$refs.postForm) {
          this.$refs.postForm.resetFields();
        }
        this.postForm = {
          postId: '',
          title: '',
          content: '',
          topicId: '',
          userId: '',
          mediaUrl: '',
          mediaType: '',
          token: localStorage.getItem('token')
        };
      });
    },
    
    // 根据专题ID获取专题名称
    getTopicName(topicId) {
      if (!topicId) return '未分类';
      const topic = this.topicOptions.find(item => item.topicId === topicId);
      return topic ? topic.topicName : '未知专题';
    }
  }
}
</script>

<style scoped>
.post-list-container {
  padding: 20px;
}

.action-bar {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.left-actions {
  display: flex;
  align-items: center;
}

.right-actions {
  display: flex;
  align-items: center;
}

.search-input {
  width: 300px;
}

.table-card {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

.operation-btns .el-button {
  padding: 7px 12px;
}

/* 帖子详情样式 */
.post-details {
  margin-bottom: 20px;
}

.post-stats {
  display: flex;
  gap: 15px;
  font-size: 14px;
  color: #606266;
}

.post-content {
  line-height: 1.8;
  padding: 15px;
  background: #fff;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  min-height: 100px;
  max-height: 300px;
  overflow-y: auto;
  white-space: pre-wrap;
  word-break: break-word;
}

.post-media {
  margin-top: 20px;
}

.media-full {
  max-width: 100%;
  max-height: 400px;
  border: 1px solid #eee;
  border-radius: 4px;
}

.file-item {
  padding: 10px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  background-color: #f5f7fa;
}

/* 媒体预览样式 */
.media-preview {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.media-item {
  width: 150px;
  height: 150px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  overflow: hidden;
  position: relative;
}

.media-thumbnail {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.file-placeholder {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  background-color: #f5f7fa;
}

.file-placeholder i {
  font-size: 36px;
  color: #909399;
}

.file-placeholder span {
  margin-top: 10px;
  font-size: 12px;
  color: #606266;
  max-width: 90%;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
</style> 